package teacher

import (
	"github.com/gin-gonic/gin"
	"github.com/go-playground/validator/v10"
	"go.uber.org/zap"
	"project/pkg/md5"
	"project/pkg/models"
	"project/pkg/validate"
	"strconv"
)

func (h THandler) Register(c *gin.Context) {
	resp := new(models.RespData)
	req := new(models.TeacherRegisterReq)
	if err := c.ShouldBindJSON(req); err != nil {
		errs, ok := err.(validator.ValidationErrors)
		if !ok {
			zap.L().Error("Student:Register with invalid fail", zap.Error(err))
			resp.SendServerBusy(c)
			return
		} else {
			zap.L().Error("Student:Register with invalid fail", zap.Error(errs))
			resp.SendCodeWithMsg(c, models.CodeInvalidParam, validate.RemoveTopStruct(errs.Translate(validate.Trans)))
			return
		}
	}
	//检查
	exist, _, err := h.M.TeacherCheckExist(req.Username)
	if err != nil {
		zap.L().Error("Student:UpdateInfo h.M.TeacherCheckExist err", zap.Error(err))
		resp.SendServerBusy(c)
		return
	}
	if exist {
		resp.SendCode(c, models.CodeUserExist)
		return
	}
	grade, _ := strconv.Atoi(req.Grade)
	teacher := &models.TeacherInfo{
		Username: req.Username,
		Password: md5.MD5(req.Password),
		WxOpenID: req.WxOpenID,
		Grade:    grade,
		Name:     req.Name,
		//ClassList: "",
	}
	err = h.M.TeacherUpdateInfoBuID(teacher)
	if err != nil {
		zap.L().Error("Student:UpdateInfo h.M.TeacherUpdateInfoBuID err", zap.Error(err))
		resp.SendServerBusy(c)
		return
	}
	resp.SendSuccess(c)
}
